package com.eeepay.eeepay_v2.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.eeepay_v2.util.ScreenShot;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static com.eeepay.eeepay_v2.activity.TestUpdateIPAct.TEST_KEY;

/**
 * 描述：分享界面
 * 1微信分享
 * 2朋友圈
 * 作者：zhuangzeqin
 * 时间: 2017/7/19-9:57
 * 邮箱：zzq@eeepay.cn
 */
public class ShareActionActivity extends ABBaseActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {
    private static final int REQUEST_CODE_SAVE_IMG = 10;//请求码
    private TextView wechat_ivew_hy;//微信分享
    private TextView wechat_ivew_py;//朋友圈分享
    private WebView webView;//webview 加载
    private TitleBar tb_title;//标题栏
    private LinearLayout linearLayout;//分割线
    private LinearLayout ll_sharelayout;//分享底部按钮

    //测试环境 地址
    private final String WEB_URL_TEST = "http://192.168.1.182:8999/core2/superPushClient/superPushShareSDB?recommendedUserId=%s";
    //正式环境地址
    private final String WEB_URL_OFFICIAL = "http://core.sqianbao.cn/core2/superPushClient/superPushShareSDB?recommendedUserId=%s";
    //add by zhuangzeqin 2017年10月19日15:12:57 准生产环境
    private final String WEB_URL_ZSC = "http://test-agentapi.sqianbao.cn/core2/superPushClient/superPushShareSDB?recommendedUserId=%s";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_share_action;
    }

    @Override
    protected void initWidget() {
        setLoadWebUrl();
        wechat_ivew_hy = getViewById(R.id.wechat_ivew_hy);
        wechat_ivew_py = getViewById(R.id.wechat_ivew_py);
        tb_title = getViewById(R.id.tb_title);
        linearLayout = getViewById(R.id.linearLayout);
        ll_sharelayout = getViewById(R.id.ll_sharelayout);
    }

    /**
     * 根据参数拦截是否要显示底部的按钮
     * @param enable
     */
    private void setVisibleEnable(final boolean enable)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (enable) {
                    tb_title.setShowRight(View.VISIBLE);
                    linearLayout.setVisibility(View.VISIBLE);
                    ll_sharelayout.setVisibility(View.VISIBLE);
                }else{
                    tb_title.setShowRight(View.GONE);
                    linearLayout.setVisibility(View.GONE);
                    ll_sharelayout.setVisibility(View.GONE);
                }
            }
        });
    }


    /**
     * 根据不同环境；选择不同weburl 加载
     */
    private void setLoadWebUrl() {
        int index = (int) SPUtils.get(TEST_KEY, 0);
        switch (index) {
            case 0://线上环境（生产环境）
                initWebView(WEB_URL_OFFICIAL);
                break;
            case 1://add by zhuangzeqin 2017年10月19日15:12:02 准生产环境
                initWebView(WEB_URL_ZSC);
                break;
            case 2://182环境
                initWebView(WEB_URL_TEST);
                break;
        }
    }

    public void initWebView(final String weburl) {
        webView = getViewById(R.id.web_shareinfo);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDatabaseEnabled(true);
        // 设置定位的数据库路径
        String dir = mContext.getDir("database", Context.MODE_PRIVATE).getPath();
        webSettings.setGeolocationDatabasePath(dir);
        // 启用地理定位
        webSettings.setGeolocationEnabled(true);
        // 加上这句话，支持html5的某些alert提示框的弹出
        webSettings.setDomStorageEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setBuiltInZoomControls(false);
        //分享的加载链接
        final String URL = String.format(weburl, UserInfo.getUserInfo2SP().getUserNo());
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showProgressDialog();
                if (url.contains("sdb-detail.html?option=true"))//add by zhuangzeqin 2017年8月22日14:59:46  当拦截到有带option 的参数是隐藏下面分享按钮
                {
                    setVisibleEnable(false);
                }
                else
                {
                    setVisibleEnable(true);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                dismissProgressDialog();
            }

            /**
             * 拦截请求
             **/
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
//                String url = request.getUrl().toString();
//                Log.d("ShareActionActivity", "shouldInterceptRequest: "+url);
                return super.shouldInterceptRequest(view, request);
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl(URL);
            }

        });
        webView.loadUrl(URL);
    }

    @Override
    protected void eventOnClick() {
        wechat_ivew_hy.setOnClickListener(this);
        wechat_ivew_py.setOnClickListener(this);
        tb_title.setLeftOnClickListener(new TitleBar.LeftBtnOnClickListener() {
            @Override
            public void onLeftClick(View view) {
                goBack();

            }
        });
        //保存按钮监听
        tb_title.setRightOnClickListener(new TitleBar.RightBtnOnClickListener() {
            @Override
            public void onRightClick(View view) {
                requestPermission();
            }
        });
    }

    /**
     * 返回上一级页面
     */
    private void goBack() {
        if(webView.canGoBack())
        {
            webView.goBack();
        }
        else
        {
            finish();
        }
    }
    /**
     * 监听Back键按下事件
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            goBack();
            return false;
        }
        return super.onKeyDown(keyCode, event);

    }

    /**
     * 保存图片
     */
    private void saveImage() {
        ScreenShot.shoot(ShareActionActivity.this, webView, new ScreenShot.ResultCallBack() {
            @Override
            public void onSuccess(File file) {
                Log.e("ShareActionActivity", "onSuccess(ShareActionActivity.java:60)" + file.getPath());
                showToast("保存成功:" + file.getPath());
            }

            @Override
            public void onFail(String error) {
                showToast(error);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            //拒绝授权后，从系统设置了授权后，返回APP进行相应的操作
            Log.i("ShareActionActivity", "onPermissionsDenied:------>自定义设置授权后返回APP");
            saveImage();
        }
    }

    /**
     * 分享信息
     * SHARE_MEDIA.WEIXIN 微信
     * SHARE_MEDIA.WEIXIN_CIRCLE 微信朋友圈
     *
     * @param shareMedia 分享平台
     */
    private void shareInfoAction(SHARE_MEDIA shareMedia) {
        Bitmap bitmap = ScreenShot.takeScreenShot(this, webView);//bitmap文件
        UMImage umImage = new UMImage(this, bitmap);
//        UMImage thumb = new UMImage(this, R.drawable.icon_all);
//        umImage.setThumb(thumb);//设置缩略图
//        umImage.setDescription("我测试了一下分享朋友的；无需点赞");
//        umImage.setTitle("666分享朋友圈");
        ShareAction shareAction = new ShareAction(this);
        shareAction.setPlatform(shareMedia);//微信 or 微信朋友圈
        shareAction.withMedia(umImage);
        shareAction.setCallback(umShareListener);
        shareAction.share();
        //-----------------------------------其它分享途径--------------------------------------
//        UMImage image = new UMImage(ShareActivity.this, "imageurl");//网络图片
//        UMImage image = new UMImage(ShareActivity.this, file);//本地文件
//        UMImage image = new UMImage(ShareActivity.this, R.drawable.xxx);//资源文件
//        UMImage image = new UMImage(ShareActivity.this, bitmap);//bitmap文件
//        UMImage image = new UMImage(ShareActivity.this, byte[]);//字节流
    }

    /**
     * 分享回调监听
     */
    private final UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param share_media 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA share_media) {
            showToast("分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param share_media 平台类型
         * @param throwable 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            Log.e("ShareActionActivity", "onError(ShareActionActivity.java:68)" + "分享失败" + throwable.getMessage());
            showToast("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            showToast("分享被取消");
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wechat_ivew_hy://微信分享
                shareInfoAction(SHARE_MEDIA.WEIXIN);
                break;
            case R.id.wechat_ivew_py://微信朋友圈分享
                shareInfoAction(SHARE_MEDIA.WEIXIN_CIRCLE);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            //读取sd卡的权限
            String[] mPermissionList = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(mContext, mPermissionList)) {
                //已经同意过
                saveImage();
            } else {
                //未同意过,或者说是拒绝了，再次申请权限
                EasyPermissions.requestPermissions(this, "保存图片需要读取sd卡的权限", REQUEST_CODE_SAVE_IMG, mPermissionList);
            }
        } else {
            saveImage();
        }
    }

    //授权结果，分发下去
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        //跳转到onPermissionsGranted或者onPermissionsDenied去回调授权结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //同意授权
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        Log.e("ShareActionActivity", "onPermissionsGranted(ShareActionActivity.java:221)" + "onPermissionsGranted:" + requestCode + ":" + perms.size());
        saveImage();
    }

    //拒绝授权
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            //打开系统设置，手动授权
            new AppSettingsDialog.Builder(this).build().show();
        }
    }
}
